package me.dao.impl;

import me.dao.StudentDao;
import me.domain.Student;
import me.util.DBManager;
import org.springframework.context.annotation.Scope;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import java.util.ArrayList;
import java.util.List;

/**
 * 定义学生与数据库交互的类
 *
 * @author Rainh
 */
@Repository(value = "studentDao")
@Scope(value = "prototype")
public class StudentDaoImpl implements StudentDao {

    //实例化JdbcTemplate对象
    private JdbcTemplate jdbcTemplate = new JdbcTemplate(DBManager.getDataSource());

    /**
     * 查询所有学生信息
     * @return
     */
    @Override
    public List<Student> queryAllStudents(){
        //定义集合保存查询到的学生信息
        List<Student> studentList = new ArrayList<Student>();
        //定义sql语句
        String sql = " select id,name,gender,age,address from tab_student ";
        try {
            //执行sql语句
            studentList = jdbcTemplate.query(sql, new BeanPropertyRowMapper<Student>(Student.class));
        } catch (Exception e) {
            e.printStackTrace();
        }

        return studentList;

    }

    /**
     * 添加学生信息
     * @param student
     */
    @Override
    public void addStudent(Student student){

        //定义sql语句
        String sql = " insert into tab_student (id,name,gender,age,address) values(?,?,?,?,?)  ";
        //执行sql语句，并且把参数也放进去
        jdbcTemplate.update(sql,student.getId(),student.getName(),
                student.getGender(),student.getAge(),student.getAddress());

    }

    /**
     * 通过ID查找一个学生信息
     * @param id
     * @return
     */
    @Override
    public Student findStudentById(long id) {
        //实例化一个空的student对象
        Student student = null;
        //定义sql语句
        String sql = " select id,name,gender,age,address from tab_student where id = ? ";
        try {
            //执行sql语句，并且把参数也放进去
            student = jdbcTemplate.queryForObject(sql, new BeanPropertyRowMapper<Student>(Student.class), id);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return student;
    }

    /**
     * 通过student对象修改student信息
     * @param student
     */
    @Override
    public void updateStudent(Student student){

        //定义sql语句
        String sql = " update tab_student set name=?,gender=?,age=?,address=? where id=? ";
        //执行sql语句，并且把参数也放进去
        jdbcTemplate.update(sql,student.getName(),student.getGender(),
                student.getAge(),student.getAddress(),student.getId());

    }

    /**
     * 通过ID删除学生信息
     * @param id
     */
    @Override
    public void deleteStudentById(long id) {

        //定义sql语句
        String sql = " delete from tab_student where id = ? ";
        //执行sql语句，并且把参数也放进去
        jdbcTemplate.update(sql, id);

    }
}
